import React from 'react';
import {
  Button,
  Col,
  DatePicker,
  Form,
  InputNumber,
  message,
  Modal,
  Row,
  Table,
  Tabs,
  Tag,
} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import ExportCode from './ExportCode';
import copy from 'copy-to-clipboard';
import axios from 'axios';

// import axios from "axios";
// import { ExportExcel } from '@/services/crud';
const { TabPane } = Tabs;
class CourseEdit extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      pageIndex: 1,
      pageSize: 10,
      loading: false,
      load: false,
      codeListTotal: 0,
      codeList: [],
      selectedRowKeys: [],
      selectedRowData: [],
      status: null,
      stateKey: '2',
      couId: '',
      selectedRowKeysCode: [],
      num: 10,
      codenum: 8,
      endtime: '',
      visible: false,
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    const { couId } = this.props;
    if (couId) {
      this.getExchangeCodeList(couId);
    }
  }
  //查询优惠券兑换码
  getExchangeCodeList = (conId: number) => {
    const { pageIndex, pageSize, status } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'Abp/getExchangeCodeList',
      payload: {
        conId,
        SkipCount: (pageIndex - 1) * pageSize,
        MaxResultCount: pageSize,
        status,
      },
    }).then(() => {
      const tempCodeList = this.props.response.result.edu_CouponExchangeDto;
      console.log(this.props.response.result);
      const tempTotal = this.props.response.result?.totalCount;
      this.setState({ codeList: tempCodeList, codeListTotal: tempTotal });
    });
  };
  //创建兑换码
  getBatchExchangeCode = () => {
    const { dispatch } = this.props;
    var datas = this.formRef.current.getFieldsValue();
    dispatch({
      type: 'Abp/getBatchExchangeCode',
      payload: {
        conId: this.props.couId,
        num: datas.num,
        codenum: datas.codenum,
        endtime: moment(datas.endtime).format('YYYY-MM-DD'),
      },
    }).then(() => {
      const response = this.props.response;
      if (response.success) {
        message.success(`已成功创建${datas.num}条兑换码！`);
      } else {
        message.error('创建失败，请检查后重新重建！');
      }
    });
  };
  //选择兑换码
  onSelectChange = (selectedRowKeys: any, selectedRowData: any) => {
    this.setState({ selectedRowKeys, selectedRowData });
    let tempCode: any = [];
    let tempCodeString = '';
    if (selectedRowData.length >= 0) {
      selectedRowData.forEach((item: any) => {
        tempCode.push(item.exchangeCode + ',' + item.status + ',' + item.endTime);
      });
      console.log(selectedRowData);
      this.setState({ selectedRowKeysCode: tempCode });

      //   this.setState({ selectedRowKeysCode: tempCodeString });
    }
  };
  //取消全选
  start = () => {
    this.setState({ load: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        load: false,
      });
    }, 1000);
  };
  //tab回调
  callback = (key: any) => {
    let state: number = parseInt(key);
    const couId = this.props.couId;
    if (state == 2) {
      this.setState({ pageIndex: 1, status: null }, () => this.getExchangeCodeList(couId));
    } else if (state == 1) {
      this.setState({ pageIndex: 1, status: 1 }, () => this.getExchangeCodeList(couId));
    } else if (state == 0) {
      this.setState({ pageIndex: 1, status: 0 }, () => this.getExchangeCodeList(couId));
    }
    this.setState({ stateKey: state });
  };
  //时间切换
  timeChange = (date: any) => {
    console.log(date.format('YYYY/MM/DD'));
    this.setState({ endtime: date.format('YYYY/MM/DD') });
  };
  //数量切换
  numChange = (e: any) => {
    console.log(e);
  };
  //位数切换
  codenumChange = (e: any) => {
    console.log(e);
  };
  //导出弹出框
  showModal = (visible: any) => {
    const { selectedRowKeysCode } = this.state;
    if (selectedRowKeysCode.length <= 0) {
      message.warning('请选择一条需要导出的兑换码！');
    } else {
      this.setState({ visible });
    }
  };
  onSubmit = async (values: any) => {
    const { fileName } = values;

    const { dispatch } = this.props;
    const { selectedRowKeysCode } = this.state;
    const postData = {
      codelist: selectedRowKeysCode,
      fileName: fileName,
    };
    // console.log(JSON.stringify(temp))
    // await dispatch({
    //     type:'Abp/exportExcel',
    //     payload:JSON.stringify(temp)
    // }).then(()=>{
    //     console.log(this.props.response);
    // })
    // axios
    //   .post('http://124.71.234.61:21021/ExcelHelper/ExportExcel', postData, {
    //     headers: {
    //       'Content-Type': 'application/json; application/octet-stream',
    //     },
    //     responseType: 'arraybuffer',
    //   })
    //   .then((res) => {
    //     var blob = new Blob([res.data], {
    //       type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
    //     }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
    //     var downloadElement = document.createElement('a');
    //     var href = window.URL.createObjectURL(blob); //创建下载的链接
    //     downloadElement.href = href;
    //     downloadElement.download = postData.fileName; //下载后文件名
    //     document.body.appendChild(downloadElement);
    //     downloadElement.click(); //点击下载
    //     document.body.removeChild(downloadElement); //下载完成移除元素
    //     window.URL.revokeObjectURL(href); //释放掉blob对象
    //   });
  };
  nSubmit = (e: any) => {
    var postData = {
      codelist: ['AAA,0,2021-12-09', 'BBB,1,2021-12-08'],
      fileName: 'hahaha',
    };
    axios
      .post('http://localhost:21021/ExcelHelper/ExportExcel', postData, {
        headers: {
          'Content-Type': 'application/json; application/octet-stream',
        },
        responseType: 'arraybuffer',
      })
      .then((res) => {
        var blob = new Blob([res.data], {
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
        }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
        var downloadElement = document.createElement('a');
        var href = window.URL.createObjectURL(blob); //创建下载的链接
        downloadElement.href = href;
        downloadElement.download = postData.fileName; //下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //点击下载
        document.body.removeChild(downloadElement); //下载完成移除元素
        window.URL.revokeObjectURL(href); //释放掉blob对象
      });
  };
  copyCode = () => {
    const { selectedRowKeysCode } = this.state;
  };
  render() {
    const {
      pageSize,
      codeList,
      codeListTotal,
      loading,
      load,
      selectedRowKeys,
      stateKey,
      num,
      codenum,
      visible,
    } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const hasSelected = selectedRowKeys.length > 0;
    const columns: any = [
      {
        title: '序号',
        width: 60,
        align: 'center',
        key: 'index',
        render: (_: any, __: any, i: any) => {
          return i + 1;
        },
      },
      {
        title: '兑换码',
        width: 120,
        align: 'center',
        dataIndex: 'exchangeCode',
        ellipsis: true,
      },
      {
        title: '兑换码状态',
        dataIndex: 'status',
        width: 120,
        align: 'center',
        render: (text: number) => {
          if (text == 0) {
            return <Tag color="green">未兑换</Tag>;
          } else {
            return <Tag color="gray">已兑换</Tag>;
          }
        },
      },
      {
        title: '兑换会员昵称',
        dataIndex: 'tMember',
        key: 'nickname',
        width: 120,
        align: 'center',
        ellipsis: true,
        render: (text: string, recode: any) => {
          if (recode.tMember) {
            return <span>{recode.tMember.nickname}</span>;
          } else {
            return <span>尚未兑换</span>;
          }
        },
      },
      {
        title: '兑换会员手机号',
        dataIndex: 'tMember',
        key: 'mobile',
        width: 120,
        align: 'center',
        ellipsis: true,
        render: (text: string, recode: any) => {
          if (recode.tMember) {
            return <span>{recode.tMember.mobile}</span>;
          } else {
            return <span>尚未兑换</span>;
          }
        },
      },
      {
        title: '创建时间',
        width: 120,
        align: 'center',
        dataIndex: 'creationTime',
        render: (text: string) => (
          <span>{text && text !== '' ? moment(text).format('YYYY-MM-DD') : ''}</span>
        ),
      },
    ];
    return (
      <div>
        <div style={{ marginBottom: '20px' }}>
          <Form
            ref={this.formRef}
            onFinish={this.getBatchExchangeCode}
            initialValues={{ num: num, codenum: codenum }}
          >
            <Row gutter={4}>
              <Col span={5}>
                <Form.Item name="num" label="创建数量" rules={[{ required: true }]}>
                  <InputNumber step={1} placeholder="请输入创建数量" style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={5}>
                <Form.Item name="codenum" label="兑换码位数" rules={[{ required: true }]}>
                  <InputNumber step={1} placeholder="请输入兑换码位数" style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item name="endtime" label="兑换码截止日期" rules={[{ required: true }]}>
                  <DatePicker placeholder="请选择兑换码截止日期" style={{ width: '100%' }} />
                </Form.Item>
              </Col>
              <Col span={4} offset={2} style={{ marginTop: '30px' }}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    生成兑换码
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
        <div>
          <Button danger onClick={this.start} disabled={!hasSelected} loading={load}>
            重选
          </Button>
          <span style={{ marginLeft: '8px' }}>
            {hasSelected ? `已选择 ${selectedRowKeys.length} 条数据` : ''}
          </span>
          <Button
            type="default"
            onClick={() => this.showModal(true)}
            style={{ marginLeft: '30px' }}
          >
            导出兑换码
          </Button>
        </div>
        <Tabs defaultActiveKey={stateKey} onChange={this.callback}>
          <TabPane tab={'全部'} key="2"></TabPane>
          <TabPane tab={'未兑换'} key="0"></TabPane>
          <TabPane tab={'已兑换'} key="1"></TabPane>
        </Tabs>
        <Table
          rowKey="id"
          loading={loading}
          columns={columns}
          dataSource={codeList}
          rowSelection={rowSelection}
          pagination={{
            onChange: (page) => {
              this.setState({ pageIndex: page }, () => {
                this.getExchangeCodeList(this.props.couId);
              });
            },
            pageSize,
            pageSizeOptions: ['10', '50', '100', '5000', '10000'],
            total: codeListTotal,
            showTotal: (totalCount) => `总计${totalCount}条数据`,
          }}
        />
        <ExportCode
          visible={visible}
          onCancel={() => this.showModal(false)}
          onSubmit={this.onSubmit}
        />
      </div>
    );
  }
}
export default connect(({ Abp, Category }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  Category,
}))(CourseEdit);
